<template>
  <div class="upload-file">
    <el-button :disabled="disabled" @click="openUpload">导入</el-button>
    <!-- 上传对话框 -->
    <el-dialog v-if="upload.open" :title="upload.title" v-model="upload.open" width="400px" append-to-body
      custom-class="dialogTable">
      <p></p>
      <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :limit="limits"
        :on-change="handleChange" :on-error="handleUploadError"
         :on-success="handleUploadSuccess" :show-file-list="false" :headers="upload.headers" class="upload-file-uploader"
        ref="uploads" :auto-upload="true" style="display: inline-block" :disabled="disabled" :fileType="fileType" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <!-- 上传提示 -->
          <div class="el-upload__tip text-center">
            <template v-if="showTip">
              请上传
              <template v-if="fileSize">大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
              <template v-if="fileType.length != 0"> 格式为 <b style="color: #f56c6c">{{ fileType.join(",") }}</b>
              </template>
              的文件
            </template>
          </div>
        </template>
      </el-upload>
      <el-upload action="#" :on-remove="handleRemove" :on-preview="preview" v-model:file-list="fileList"  :show-file-list="true" class="upload-file-uploader"
        ref="uploadss" :auto-upload="false">
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" :disabled="(fileList.length == 0) || (isSpatialData == '1' && uploadDisabled)" @click="submitFileForm">确 定</el-button> -->
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="(upload.open = false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { getParseShp, getAttachByIds } from "@/api/slideAssess/levelAnalyse";

const props = defineProps({
  attachId: {
    type: String,
    default: null,
  },
  // 数量限制
  limit: {
    type: Number,
    default: 6,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 200,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    //default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    default: () => [],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  taskId: {
    type: String,
    default: '',
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const fileList = ref([]);
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const limits = 6;
const uploadFileUrl =ref(import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile");// 上传的文件服务器地址
/*** 用户导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "tokrn " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile", // 上传的图片服务器地址
});

watch(() => upload, val => {
  if (upload.open&&props.attachId) {
    getAttachByIds({attachId:props.attachId}).then(res=>{
      let {data} = res
      let temp = 1;
      // 首先将值转为数组
      const list = Array.isArray(data) ? data : [];
      console.log(list,'hahhaha');
      // 然后将数组转为对象数组
      // fileList.value = list.map(item => {
      //   item.attachId = item.attachId;
      //   item.name = item.attachName;
      //   item.url = item.attachPath;
      //   return item;
      // });
      list.forEach(item=>{
        fileList.value.push({
          name: item.attachName,
          url: item.attachPath,
          attachId:item.attachId
        })
      })
    }).catch(()=>{fileList.value = [];})
  } else {
    fileList.value = [];
  }
}, { deep: true});

function openUpload() {
    // uploadDisabled.value = true;
    fileList.value = [];
    upload.title = "上传";
    upload.open = true;
}

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    const isTypeOk = props.fileType.some((type) => {
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }

  if (fileList.value.length) {
      let shp = 0;
      let dbf = 0;
      let prj = 0;
      let shx = 0;
      let cpg = 0;
      let qmd = 0;
      var falg1 =fileList.value.some(item => {
        let typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
        if(typeName == 'shp'){
          shp++;
          if(shp>1){
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg、qmd类型文件只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'dbf'){
          dbf++;
          if(dbf>1){
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg、qmd类型文件只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'prj'){
          prj++;
          if(prj>1){
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg、qmd类型文件只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'shx'){
          shx++;
          if(shx>1){
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg、qmd类型文件只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'cpg'){
          cpg++;
          if(cpg>1){
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg、qmd类型文件只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'qmd'){
          qmd++;
          if(qmd>1){
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg、qmd类型文件只能上传一个!`);
            return true;
          }
        }
      })
      if (falg1) { return false; }
    }

  // 校检文件大小
  if (props.fileSize) {
      var isLt1 = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt1) {
        proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
        return false;
      }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  upload.isUploading = true;
  number.value++;
  return true;
}

function handleChange(file, fileList) {
  fileList.value = fileList;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code == 200) {
    fileList.value.push({ attachId: res.data[0].attachId, name: res.data[0].attachName, url: res.data[0].attachPath });
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("上传文件成功");
  }else if(res.code == 500){
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("上传文件失败");
  }
}

function submitFileForm(){
  let nameArr = []
  fileList.value.forEach(item => {
      const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
      nameArr.push(typeName)
    })
    if(nameArr.includes('shp')&&nameArr.includes('dbf')&&nameArr.includes('prj')&&nameArr.includes('shx')&&nameArr.includes('cpg')&&nameArr.includes('qmd')&& fileList.value.length==6){
  // if(nameArr.includes('shp' && 'dbf' && 'prj' && 'shx' && 'cpg' && 'qmd')&&fileList.value.length==6){
    let ids = fileList.value.map(item=>item.attachId).join(',')
    proxy.$modal.loading("正在解析文件，请稍候...");
    getParseShp({taskId:props.taskId,fileId:ids}).then(res=>{
      upload.open = false;
      emit('sureUploadFile', {ids:ids,lithologyVersion1:res.data});
      proxy.$modal.closeLoading()
    }).catch(()=>{proxy.$modal.closeLoading()})
  }else{
    proxy.$modal.msgError(`请上传shp、dbf、prj、shx、cpg、qmd类型文件且文件只能上传一个!`);
  }
}

// 删除文件
function handleRemove(file, uploadFiles) {
  // const index = fileList.value.findIndex(item => item.attachId === file.attachId)
  // fileList.value.splice(index, 1)
  console.log(file,'lalal');
  console.log(fileList.value,'lalal');
}


// 下载文件
function preview(file) {
  var query = {
    attachId: file.attachId,
    name: file.attachName
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

defineExpose({
  fileList
});
</script>

<style scoped lang="scss">
.upload-file {
  width: 100%;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.el-upload-list__item-name {
  width: 310px !important;
  // white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
